import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const baseURL = process.env.NODE_ENV === 'production' ?
  process.env.VUE_APP_API_BASE_URL:
  // 'https://web01.alai04.net/api'
  // 'https://dev.ikariagroup.com/api'
  'http://192.168.0.21:8000/api'
// 'http://192.168.0.244:8000/api'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL: process.env.VUE_APP_API_BASE_URL,
  headers:{
    'Cache-Control':'no-cache'
  },
  baseURL,
  timeout: process.env.NODE_ENV === 'production'?30000:20000 // 请求超时时间
})
const logout = ()=>{
  store.dispatch('Logout').then(() => {
    setTimeout(() => {
      window.location.reload()
    }, 1500)
  })
}
// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if ([500, 503].includes(error.response.status)) {
      notification.error({
        message: '服务器错误',
      })
    }
    if (error.response.status === 401) {
      notification.error({
        message: '登录过期',
        description: '登录时效已过期，请重新登录'
      })
      logout()
    }
    if (error.response.status === 403 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: '没有权限访问',
        description: '权限验证失败'
      })
      if (token) {
        logout()
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  if(!response.data){
    throw new Error('服务器出错了')
  }
  if ('errorCode' in response.data) {
    if(response.data.errorCode === 0){
      return response.data
    }
    else{
      notification.error({
        message: response.data.message || '服务器出错了',
      })
      throw new Error('服务器出错了')
    }
  }else if(response.data.code == 401){
      notification.error({
        message: '登录过期',
        description: '登录时效已过期，请重新登录'
      })
      logout()
    } else {
    notification.error({
      message: response.data.detail || '服务器出错了',
    })
    throw new Error('服务器出错了')
  }
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
